# Copyright 2006 Michael Gorsuch <michael@styledbits.com>

# This file is part of GrabTheMic <http://www.grabthemic.org>.

# GrabTheMic is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

class UserController < ApplicationController
  before_filter :authorize, :only => [:edit, :update]
  layout "default"
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :create, :update ],
         :redirect_to => { :action => :list }

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      session[:user_id] = @user.id
      flash[:notice] = 'Your new account was successfully created.'
      AlertMailer.deliver_new_user @user
      redirect_to :controller => "story", :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @user = get_user
  end

  def update
    @user = get_user
    if @user.update_attributes(params[:user])
      flash[:notice] = 'User was successfully updated.'
      redirect_to :controller => "story", :action => "list"
    else
      render :action => 'edit'
    end
  end
  
  def login
      
  end
  
  def logout
    reset_session
    redirect_to :controller => "story", :action => "list", :order => "top"
  end
  
  def verify_login
    user = User.login(params[:email], params[:password])  
    if user
      flash[:notice] = "Good to see you, #{user.name}."
      session[:user_id] = user.id
      if params[:return_to]
         redirect_to params[:return_to]
      else
        redirect_to :controller => "story", :action => "list", :order => "top"   
      end
    else
      flash[:notice] = "Could not log you in."
      render :action => "login"
    end
  end
    
end
